"""
    sentiment.py
    使用情感分析的方法对热搜内容进行分析

    目的：对于某个未来事件的情感得分，政府出台响应的政策
"""
from scipy.signal import find_peaks
from snownlp import SnowNLP
from data import read_data
import matplotlib.pyplot as plt
import seaborn as sns
from data import titles_by_date


def sentiment(data, is_plot=False):
    """
    使用情感分析，计算每日关键词的情感分布，绘制折线图
    :param data: 待分析数据
    :return: 情感高峰和低谷对应的日期和标题
    """
    data['sentiment'] = data['title'].apply(lambda x: SnowNLP(x).sentiments)

    sentiment_by_date = data.groupby('date')['sentiment'].mean()
    peaks, _ = find_peaks(sentiment_by_date, prominence=0.01)
    throughs, _ = find_peaks(-sentiment_by_date, prominence=0.01)

    peak_dates = sentiment_by_date.index[peaks]
    peak_values = sentiment_by_date.iloc[peaks]
    through_dates = sentiment_by_date.index[throughs]
    through_values = sentiment_by_date.iloc[throughs]

    if is_plot:
        plt.figure(figsize=(12, 6))
        sns.lineplot(data=sentiment_by_date)
        plt.title('Daily Sentiment Trend Over Time')
        plt.xlabel('Date')
        plt.ylabel('Average Sentiment Score')
        plt.xticks(rotation=45)
        plt.grid(True)

        plt.scatter(peak_dates, peak_values, color='green', s=30, zorder=5)

        plt.scatter(through_dates, through_values, color='red', s=30, zorder=5)
        # plt.show()
        plt.savefig('images/sentiment-peak.png')

        # 不聚合日期，绘制每日的情感分布
        plt.figure(figsize=(12, 6))
        sns.lineplot(x='date', y='sentiment', data=data)
        plt.title('Sentiment Distribution Over Time')
        plt.xlabel('Date')
        plt.ylabel('Sentiment Score')
        # plt.show()
        plt.savefig('images/sentiment-dis.png')

    return peak_dates, peak_values, through_dates, through_values


def senti_analysis(data, dates, scores):
    """
    展示：日期-标题-情感得分
    :param data: 待分析数据
    :param dates: 待分析日期
    :param scores: 待分析日期对应的情感得分
    :return: 元组列表，每个元组包含日期、标题、情感得分
    """
    # 日期-标题-情感得分
    date_title_score = []
    dates = [str(date).split(' ')[0] for date in dates]
    dates_and_titles = titles_by_date(data, dates)

    for date_itle, score in zip(dates_and_titles, scores):
        date_title_score.append((date_itle[0], date_itle[1], score))

    return date_title_score


if __name__ == '__main__':
    data = read_data('res/Weibo_2020Coron.xlsx')
    peak_dates, peak_values, _, _ = sentiment(data, is_plot=True)
    # print(peak_dates)
    result = senti_analysis(data, peak_dates, peak_values)

    # 根据不同方法定位到日期
    # 根据日期查看当天搜索量前x的标题
    # 根据数据和标题，人工判断是否合理
    for x in result:
        print(x)
